<?php

/**
 * 登陆控制器
 *
 * @author dalei.chen
 */

require 'CommonController.php';

class Admin_UdidReportController extends Admin_CommonController
{
    /**
     * 
     * 路径密码
     */
    private $_passid = 'yekbi123';
    private $_currAction = '';
    private $_productcode = '';
    private $_reportFile = '';
    private $_reportDay = '';

    /**
     * 初始化
     * 
     * @return void
     */
    public function init()
    {
        $this->_loginIsCheck = 0;
        parent::init();
        $this->view->title = $this->_configs['project']['systemName'] . " - 管理中心";
        $this->_model = new Application_Model_UdidReport();
        $this->_productModel = new Application_Model_PartnerProduct();
        $this->_ddModel = new Application_Model_DayData();
        $this->dayAreaDataModel = new Application_Model_DayAreaData();
        $this->sourceModel = new Application_Model_Source();
        $this->memberModel = new Application_Model_Member();
        $this->_reportDay = date('Y-m-d',strtotime(("-1 day")));
       
    }
     /**
     * 获取报表TITLE(默认为昨天)
     */
    public function getFileDay()
    {
    	return $this->_reportDay;
    }
    
    /**
     * 获取日报发送时间(默认为昨天)
     */
    public function getPositionDay()
    {
    	return $this->_reportDay;
    }
    /**
     * 获取指定日期的时间戳(默认为昨天)
     */
    public function getPositionStamp()
    {
    	return strtotime($this->_reportDay);
    }


    /**
     * 报表导出，
     * 发送下载地址 $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/dayData/';
     * 生成表格
     * 发送信息到邮箱
     * 
     * @return void
     */
    public function reportAction()
    {
         if($this->_request->get('id')!=$this->_passid){
            exit('非法访问');
        } else {
            $startTime = $this->getPositionDay();
            $year = date('Y');
            $month = date('m');
            $day = date('d');

            //获取搜有需要发送的报表产品编号
            $productCodes = $this->_productModel->udidReportProduct();
            
            foreach ($productCodes as $productCode) {
                $product = $this->_productModel->fetchRow("code = '{$productCode}'");
                $productName = $product['name'];
                
                //获取以天为单位自动导出 UDID，操作系统(iOS或者android) ， 
                //激活时间，操作系统版本号，app版本号，来源渠道名称，SourceID
                $udidRow = $this->dayUdid($startTime, $productCode);
                $keyUdidArr = array('Udid','操作系统','激活时间','操作系统版本号','app版本号','渠道名称','SourceID');
                
                
                $keyActivationAnalytics = array('名称','激活数量','激活占比(%)', '激活带来的订单量', '激活带来的占比(%)','激活带来的订单金额(￥)');
                //获取激活量 - 渠道
                $activationAnalyticsMemberRow = $this->activationAnalytics(1, $startTime, $productCode);
                
                //获取激活量 - 操作系统
                $activationAnalyticsOsRow = $this->activationAnalytics(3, $startTime, $productCode);
                
                //获取激活量 - 地狱
                $activationAnalyticsAreaRow = $this->activationAnalytics(4, $startTime, $productCode);

                $yestoday = $this->getFileDay();
                
                //整合数据
                //udid数据
                $dataUdid = array(
                     'title'=>'UDID对比',
                    'headLine'=>$keyUdidArr,
                    'bodyLines'=>$udidRow
                );
                
                //激活量数据
                $dataInstall = array (
                array(
                'title'=>'渠道',
                'headLine'=>$keyActivationAnalytics,
                'bodyLines'=>$activationAnalyticsMemberRow
                ),
                array(
                'title'=>'操作系统',
                'headLine'=>$keyActivationAnalytics,
                'bodyLines'=>$activationAnalyticsOsRow
                ),
                array(
                'title'=>'地域',
                'headLine'=>$keyActivationAnalytics,
                'bodyLines'=>$activationAnalyticsAreaRow
                )
                );
                //写入到UDID日报
                $udidFile = $this->_model->writeToExcel('udid',$this->getFileDay().' '.$productName.'-UDID日报',$dataUdid['bodyLines'],$productCode,$dataUdid['headLine'],'Udid日报');
                
                //写入到激活量分析日报
                $installReportFile = $this->_model->writeToExceInstall('install', $this->getFileDay().' '.$productName.' 激活量日报 ',$dataInstall,$productCode,$productName);
                
                //发送邮件到用户邮件
                $mailList = $this->_productModel->getUdidReportMailList($productCode);
                $to = array();
                foreach ($mailList as $mail) {
                    $to[]=array(
                    'name'=>$mail,'email'=>$mail
                     );
                }                     
                if (count($to)) {
                    $mainMail = $product['udidReportMail']? $product['udidReportMail']:$to[0]; 
                     //加载ZIP类
                      Zend_Loader::loadClass('Project_PclZip');
                      $attFilePath = PUBLIC_PATH . "/data/udidReport/".$productCode.'_'.date('YmdHis').'_install_udid_archive.zip';
                      if(file_exists($attFilePath)) {
                          unset($attFilePath);
                      }
                      $archive = new Project_PclZip($attFilePath);
                      
                      $vList[] = $archive->add(PUBLIC_PATH . "/data/udidReport/".$udidFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/udidReport/");                                              
                      $vList[] = $archive->add(PUBLIC_PATH . "/data/udidReport/".$installReportFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/udidReport/");    
                                             
                      foreach ($vList as $item) {
                          if ($item == 0) {
                              die("Error : ".$archive->errorInfo(true));
                          }
                      }
                      $atts = array(
                            array('filename'=>$this->getFileDay().'_'.$productCode.'_att.zip','path'=>$attFilePath,'type'=>'application/zip')
                        ); 
                    $data[] = $dataUdid;
                    foreach ($dataInstall as $item) {
                    	array_push($data, $item);
                    }
                    $this->_model->sendMail($data,$productName.' '.$startTime.' 激活量分析日报','激活量分析日报',$productName,$mainMail,$to,$atts);      
                }

                //发送邮件到用户邮件
                $mailListOther = $this->_configs['project']['reportTestMail'];
                $toOtherError = array();
                foreach ($mailListOther as $mail) {
                    $toOtherError[]=array(
                    'name'=>$mail,'email'=>$mail
                     );
                }
            }
        } exit();
    }
    
    /**
     * 激活量分析列表
     * @parm int $doType
     * @parm string $startTime
     * @parm string $produtCode 
     * 
     * @return array
     */
    public function activationAnalytics($doType,$startTime,$productCode)
    {
        $vars = array();
        $wheres = array();
        $vars['dateType'] = trim($this->_request->get('dateType')) ? trim($this->_request->get('dateType')) : 1;
        $vars['doType'] = $doType;
        $vars['startTime'] = $startTime . ' 0:0:0';
        $vars['endTime'] = $startTime . ' 23:59:59';
        $wheres[] = "s.productCode = '{$productCode}'";
        
        if ($vars['startTime'] != '') {
            $wheres[] = " s.date >= '{$vars['startTime']}' ";
        }
        if ($vars['endTime'] != '') {
            $wheres[] = " s.date <= '{$vars['endTime']}' ";
        }
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $group = '';
        if ($vars['doType'] == 3) {//操作系统分析
            $group = " GROUP BY s.osName ";
            $sql = "SELECT s.osName AS name,sum(s.installNum) AS installNum,sum(s.installOkOrderAmount) AS amount,sum(s.installOkOrderNum) AS installOkOrderNum
             FROM " . $this->_ddModel->getTableName() . " AS s " . $where . $group;
            $row = $this->_ddModel->getAdapter()->fetchAll($sql);
            $rowAmount = 0;
            foreach ($row as $item) {
                $rowAmount += $item['amount'];
            }
            $tmpArray = array();
            $tmpArray = $rowAmount == 0 ? $row : sysSortArray($row,'installNum',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            
            $amountTotal = 0;
            $installOkOrderNumTotal = 0;
            $installNumTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name'])) {
                    $tmpArray[$key]['name'] = '未知';
                }
                $installNumTotal += $val['installNum'];
                $amountTotal += $val['amount'];
                $installOkOrderNumTotal += $val['installOkOrderNum'];
            }

            //总计数据
            $totalArray = array('name'=>'总计','installNumTotal' => $installNumTotal, 'amountTotal' => number_format($amountTotal, 2), 'installOkOrderNumTotal' => $installOkOrderNumTotal);
            if ($totalArray['installNumTotal'] == 0) {
                $totalArray['installNumTotalPer'] = '--';
            } else {
                $totalArray['installNumTotalPer'] = '100%';
            }
            if ($totalArray['installOkOrderNumTotal'] == 0) {
                $totalArray['installOkOrderNumTotalPer'] = '--';
            } else {
                $totalArray['installOkOrderNumTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['installNumPer'] = $installNumTotal == 0 ? 0 : round($val['installNum']/$installNumTotal ,4) * 100;
                $tmpArray[$key]['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($val['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal, 2) * 100;
            }

            //金额占比小于百分之一数据的计算
            $endArray = array('name' => '其他', 'installNum' =>0, 'amount' => 0, 'installNumPer' => 0, 'amountPer' => 0 , 'installOkOrderNum' => 0, 'installOkOrderNumPer' => 0 );
            foreach ($tmpArray as $key => $val) {
                if ($val['installNumPer'] < 0) {
                    $endArray['amount'] += $val['amount'];
                    $endArray['installNum'] += $val['installNum'];
                    $endArray['installOkOrderNum'] += $val['installOkOrderNum'];
                    unset($tmpArray[$key]);
                }
            }
            if ($endArray['installNum'] != 0) {
                $endArray['installNumPer'] = $installNumTotal == 0 ? 0 : round($endArray['installNum']/$installNumTotal ,4) * 100;
                $endArray['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($endArray['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[] = $endArray;
            }
            
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                if ($tmpArray[$key]['installNumPer'] >= 100) {
                    $tmpArray[$key]['installNumPer'] = 100;
                }
            }
        } else if($vars['doType'] == 4) {//地狱分析
            $group = " GROUP BY s.province ";
            $sql = "SELECT s.province AS name,sum(s.installNum) AS installNum,sum(s.installOkOrderAmount) AS amount,sum(s.installOkOrderNum) AS installOkOrderNum
             FROM " . $this->dayAreaDataModel->getTableName() . " AS s " . $where . $group;
            $row = $this->_ddModel->getAdapter()->fetchAll($sql);
            $rowAmount = 0;
            foreach ($row as $item) {
                $rowAmount += $item['amount'];
            }
            $tmpArray = array();
            $tmpArray = $rowAmount == 0 ? $row : sysSortArray($row,'installNum',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            
            $amountTotal = 0;
            $installOkOrderNumTotal = 0;
            $installNumTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name']) || $val['name'] == '其他') {
                    $tmpArray[$key]['name'] = '国外';
                }
                $installNumTotal += $val['installNum'];
                $amountTotal += $val['amount'];
                $installOkOrderNumTotal += $val['installOkOrderNum'];
            }

            //总计数据
            $totalArray = array('name'=>'总计','installNumTotal' => $installNumTotal, 'amountTotal' => number_format($amountTotal, 2), 'installOkOrderNumTotal' => $installOkOrderNumTotal);
            if ($totalArray['installNumTotal'] == 0) {
                $totalArray['installNumTotalPer'] = '--';
            } else {
                $totalArray['installNumTotalPer'] = '100%';
            }
            if ($totalArray['installOkOrderNumTotal'] == 0) {
                $totalArray['installOkOrderNumTotalPer'] = '--';
            } else {
                $totalArray['installOkOrderNumTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['installNumPer'] = $installNumTotal == 0 ? 0 : round($val['installNum']/$installNumTotal ,4) * 100;
                $tmpArray[$key]['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($val['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal, 2) * 100;
                if ($val['amount'] == 0 && $val['installNum'] == 0 && $val['installOkOrderNum'] == 0) {
                    unset($tmpArray[$key]);
                }
            }

            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                if ($tmpArray[$key]['installNumPer'] >= 100) {
                    $tmpArray[$key]['installNumPer'] = 100;
                }
            }
        } else { //按照渠道分析
            $group = " GROUP BY m.code ";
            $sql = "SELECT m.code,m.name,s.sourceId,s.sourceSubId,s.productCode,sum(s.installNum) AS installNum,sum(s.installOkOrderAmount) AS amount,sum(s.installOkOrderNum)
             AS installOkOrderNum 
            FROM " . $this->_ddModel->getTableName() . " AS s LEFT JOIN " . $this->sourceModel->getTableName() .
             " AS u ON s.productCode = u.productCode AND s.sourceId = u.sourceId AND s.sourceSubId = u.sourceSubId LEFT JOIN " .
            $this->memberModel->getTableName() . " AS m ON u.memberCode = m.code " . $where . $group;
            $row = $this->_ddModel->getAdapter()->fetchAll($sql);
            $rowAmount = 0;
            foreach ($row as $item) {
                $rowAmount += $item['amount'];
            }
            $tmpArray = array();
            $tmpArray = $rowAmount == 0 ? $row : sysSortArray($row,'installNum',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            
            $amountTotal = 0;
            $installOkOrderNumTotal = 0;
            $installNumTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name'])) {
                    $tmpArray[$key]['name'] = '未知';
                }
                $installNumTotal += $val['installNum'];
                $amountTotal += $val['amount'];
                $installOkOrderNumTotal += $val['installOkOrderNum'];
            }

            //总计数据
            $totalArray = array('name'=>'总计','installNumTotal' => $installNumTotal, 'amountTotal' => number_format($amountTotal, 2), 'installOkOrderNumTotal' => $installOkOrderNumTotal);
            if ($totalArray['installNumTotal'] == 0) {
                $totalArray['installNumTotalPer'] = '--';
            } else {
                $totalArray['installNumTotalPer'] = '100%';
            }
            if ($totalArray['installOkOrderNumTotal'] == 0) {
                $totalArray['installOkOrderNumTotalPer'] = '--';
            } else {
                $totalArray['installOkOrderNumTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['installNumPer'] = $installNumTotal == 0 ? 0 : round($val['installNum']/$installNumTotal ,4) * 100;
                $tmpArray[$key]['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($val['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal, 2) * 100;
            }
            //金额占比小于百分之一数据的计算
            $endArray = array('code' => 'other', 'name' => '其他', 'installNum' =>0, 'amount' => 0, 'installNumPer' => 0, 'amountPer' => 0 , 'installOkOrderNum' => 0, 'installOkOrderNumPer' => 0, 'strCode' => '');
            $arrayCode = array();
            foreach ($tmpArray as $key => $val) {
                if ($val['installNumPer'] < 0) {
                    $endArray['amount'] += $val['amount'];
                    $endArray['installNum'] += $val['installNum'];
                    $endArray['installOkOrderNum'] += $val['installOkOrderNum'];
                    $arrayCode[] = $val['code'];
                    unset($tmpArray[$key]);
                }
            }
            if ($endArray['installNum'] != 0) {
                $endArray['installNumPer'] = $installNumTotal == 0 ? 0 : round($endArray['installNum']/$installNumTotal ,4) * 100;
                $endArray['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($endArray['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $endArray['strCode'] = implode(',', $arrayCode);
                $tmpArray[] = $endArray;
            }
            
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                if ($tmpArray[$key]['installNumPer'] >= 100) {
                    $tmpArray[$key]['installNumPer'] = 100;
                }
            }
        }
        
        $tmpArray[count($tmpArray)] = $totalArray;
        $tmpArray = $this->sortArr($tmpArray);
        return $tmpArray;
    }
    /**
     * 将数据进行排序
     */
    public function sortArr($arr) 
    {
    	$rows = array();
    	$sort = array('name','installNum','installNumPer','installOkOrderNum','installOkOrderNumPer','amount');
    	$totalSort = array('name','installNumTotal','installNumTotalPer','installOkOrderNumTotal',
    	'installOkOrderNumTotalPer','amountTotal'
    	);
    	foreach ($arr as $key=>$line) {
    		$row = array();
    		if ($key != count($arr)-1) {
    			foreach ($sort as $k) {
    				$row[$k] = $line[$k];
    			}
    		} else {
    		foreach ($totalSort as $k) {
    				$row[$k] = $line[$k];
    			}
    		}
    		$rows[] = $row;
    	}
    	return $rows;
    	
    }
    /**
     * 获取昨天的装机数据
     * @param string $startTime
     * @param string $productCode
     * @return array
     */
   public function dayUdid($startTime, $productCode)
   {
       return $this->_model->getUdidDayData($startTime, $productCode);
   }
}